package com.yunji.system.service;

import com.yunji.common.enums.common.UserType;
import com.yunji.common.model.dto.LoginInfo;
import com.yunji.common.model.enums.LoginTypeEnum;
import com.yunji.common.utils.StringUtils;
import com.yunji.common.utils.bean.BeanUtils;
import com.yunji.common.utils.http.ServletUtils;
import com.yunji.common.utils.ip.AddressUtils;
import com.yunji.common.utils.ip.IpUtils;
import com.yunji.system.context.SystemUtil;
import com.yunji.system.mapper.ISysCommonMapper;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.yunji.common.constant.CacheCode.LOGIN_TOKEN_KEY;
import static com.yunji.common.constant.Constants.*;
import static com.yunji.common.constant.General.TOKEN_PREFIX;

/**
 * token验证处理
 *
 * @author yunji
 */
@Component
public class TokenService {
    private static final Logger logs = LoggerFactory.getLogger(TokenService.class);

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Resource
    private ISysCommonMapper commonMapper;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Resource
    private HttpServletRequest request;

    public static String getTokenKey(String tokenKey) {
        return LOGIN_TOKEN_KEY + tokenKey;
    }

    public static String getTokenKey(LoginTypeEnum typeEnum, Long userId) {
        return LOGIN_TOKEN_KEY + typeEnum.name() + "_" + userId;
    }

    /**
     * @Title refreshToken
     * @Desc 刷新令牌有效期
     * @Date 2024-04-07 10:26:16
     */
    public void refreshToken(LoginInfo info) {
        info.setLoginTime(System.currentTimeMillis());
        info.setExpireTime(info.getLoginTime() + expireTime * MILLIS_MINUTE);
        String tokenKey = info.getTokenKey();
        // 根据uuid将loginUser缓存
        SystemUtil.redisCache().set(tokenKey, info, expireTime, TimeUnit.MINUTES);
//        LoginInfo info = new LoginInfo();
//        info.setUserId(loginUser.getUserId());
//        info.setUserName(loginUser.getUsername());
//
//        info.setBelongId(user.getBelongId());
//        info.setNickName(user.getNickName());
//        info.setPhone(user.getPhonenumber());
//        info.setUserType(user.getUserType());
        //   SystemUtil.redisCache().set((REDIS_USER_KEY + tokenKey), info, expireTime, TimeUnit.MINUTES);
        // 将同一个所属的登录信息存在一块 号进行删除
        if (!info.getUserType().equals(UserType.USER.getCode()))
        SystemUtil.redisCache().set(StringUtils.format(REDIS_BELONG_UUID, info.getBelongId()) + info.getUserId(), tokenKey, expireTime, TimeUnit.MINUTES);
    }

    /**
     * @return String 令牌
     * @Title createToken
     * @Desc 创建JWT令牌
     * @Date 2024-04-07 10:25:18
     * @Param loginUser 登录用户信息
     */
    public String createToken(LoginInfo info) {
        info.setTokenKey(getTokenKey(info.getLoginType(), info.getUserId()));
        setUserAgent(info);
        Map<String, Object> claims = new HashMap<>();
        claims.put(LOGIN_USER_KEY, info.getTokenKey());
        String token = createToken(claims);
        info.setTokenValue(token);
        refreshToken(info);
        return token;
    }

    /**
     * @return String Token令牌
     * @Title createToken
     * @Desc 从数据声明生成令牌
     * @Date 2024-04-07 10:30:37
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * @return Claims 数据声明
     * @Title parseToken
     * @Desc 从令牌中获取数据声明
     * @Date 2024-04-07 10:20:58
     */
    private Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }


    /**
     * @return LoginUser 登录用户信息
     * @Title getLoginUser
     * @Desc 获取用户身份信息
     * @Date 2024-04-07 10:22:17
     */
    public LoginInfo getLoginUser() {
        // 获取请求携带的令牌
        String token = getToken();
        if (BeanUtils.isNull(token)) {
            return null;
        }
        try {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String tokenKey = (String) claims.get(LOGIN_USER_KEY);
            return SystemUtil.redisCache().get(tokenKey);
        } catch (Exception e) {
            logs.error("获取用户信息异常'{}'", e.getMessage());
        }
        return null;
    }

    /**
     * @Title verifyToken
     * @Desc 验证令牌有效期, 相差不足20分钟, 自动刷新缓存
     * @Date 2024-04-07 10:27:40
     * @Param loginUser 登录用户信息
     */
    public void verifyToken(LoginInfo loginInfo) {
        long tokenExpire = loginInfo.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (tokenExpire - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginInfo);
        }
    }

    /**
     * @Title setLoginUser
     * @Desc 更新用户身份信息
     * @Date 2024-04-07 10:28:41
     * @Param loginUser 登录用户信息
     */
    public void setLoginUser(LoginInfo loginUser) {
        if (BeanUtils.isNull(loginUser) || BeanUtils.isNull(loginUser.getTokenKey())) {
            return;
        }
        refreshToken(loginUser);
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (BeanUtils.isNull(token)) {
            return;
        }
        String userKey = getTokenKey(token);
        SystemUtil.redisCache().delete(userKey);
    }

    /**
     * 设置用户代理信息
     *
     * @param info 登录信息
     */
    public void setUserAgent(LoginInfo info) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        info.setIpaddr(ip);
        info.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        info.setBrowser(userAgent.getBrowser().getName());
        info.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * @return String 获取请求头中Token
     * @Title getToken
     * @Desc 获取请求Token
     * @Date 2024-04-07 15:07:02
     */
    private String getToken() {
        try {
            RequestContextHolder.currentRequestAttributes();
        } catch (Exception e) {
            return null;
        }
        String token = request.getHeader(header);
        if (BeanUtils.isNotNull(token) && token.startsWith(TOKEN_PREFIX)) {
            token = token.replace(TOKEN_PREFIX, STR_NULL);
        }
        return token;
    }

    public LoginInfo getUser() {
        // 获取请求携带的令牌
        String token = getToken();
        try {
            if (BeanUtils.isNull(token)) {
                return null;
            }
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String tokenKey = (String) claims.get(LOGIN_USER_KEY);
            return SystemUtil.redisCache().get(tokenKey);
        } catch (Exception e) {
            logs.warn("【员工用户】获取解析Token异常'{}'", e.getMessage());
        }
        return null;
    }
}

